import axios from 'axios';
import store from '../store/index'
import router from '../router'
import session from '../util/session-storage'

axios.defaults.timeout = 20000;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.baseURL = '/api';


import {  Message  } from 'element-ui';

axios.interceptors.request.use(
    config => {
        // -头部token
        if (session.getItem('token')) {
            config.headers.Authorization = `${'bearer '}${session.getItem('token')}`;
        }
        // -合并两个obj对象 ES5
        return Object.assign({}, config);
    },
    err => {
        
    }
);


// axios请求拦截
axios.interceptors.response.use((res) => {
    // console.log('路由拦截',res)
    // 判断当前请求数据是否正确
    var data = res.data;
    if(data.code == 0 || data.code == '0'){
        return Promise.resolve(data);
    }else{
        Message({
            message: data.message,
            type: 'error'
        })
        return Promise.reject(res);
    }
})



/**
 * 封装post方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params)
        .then(response => {
            resolve(response.data);
        }, err => {
            reject(err);
        })
        .catch((error) => {
            reject(error)
        })
    })
}

/**
 * 封装get请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, params)
            .then(response => {
                if (response) {
                    resolve(response.data);
                }
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function patch(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.patch(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function put(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.put(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}

/**
 * 封装del请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function del(url, params) {
    return new Promise((resolve, reject) => {
        axios.delete(url, { data: params })
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}
